import * as vscode from "vscode";
import PreData, { formatData } from "./docs";
const fs = require("fs");
const path = require("path");

export function activate(context: vscode.ExtensionContext) {
    console.log('Congratulations, your extension "hover" is now active!');

    let docsObj = PreData;

    // const isHaveDocsObj = context.globalState.get("docsObj") as typeof PreData;
    const prevFileDir = context.globalState.get("prevFileDir") as string;

    if (prevFileDir) {
        loadFile(prevFileDir);
    }

    // console.log("isHaveDocsObj:", typeof isHaveDocsObj);

    // let docsObj = isHaveDocsObj && typeof isHaveDocsObj === "string" ? JSON.parse(isHaveDocsObj) : PreData;

    const otherParamsRegExp = new RegExp(/\, *(\d+)/);

    function provideHover(document: vscode.TextDocument, position: vscode.Position) {
        const queryByWord = () => {
            // 选中的单词
            const word = document.getText(document.getWordRangeAtPosition(position));

            if (docsObj[word]) {
                // 查找这个数字后面的参数
                const line = document.lineAt(position);

                const lineText = line.text.substring(position.character);

                const otherParams = lineText.match(otherParamsRegExp);

                if (!otherParams) {
                    return new vscode.Hover([docsObj[word].desc as string, docsObj[word].line as string]);
                }

                const secondObj = docsObj[word][otherParams[1]];
                const desc = <Record<string, string>>secondObj;

                if (desc) {
                    return new vscode.Hover([desc.desc, desc.line]);
                }
            }
        };

        const editor = vscode.window.activeTextEditor;

        if (editor) {
            // 获取选中的文本
            const selection = editor.selection;
            const selectedText = editor.document.getText(selection);
            // console.log(selectedText);

            if (!selectedText) {
                return queryByWord();
            } else {
                // 确认 鼠标所在行 和 选中内容行 相同
                if (position.line === selection.start.line) {
                    const getParamsRegExp = new RegExp(/\(? *(\d*) *\,? *(\d*)?/);
                    const getParams = selectedText.match(getParamsRegExp);

                    if (getParams && getParams.length) {
                        // (301)
                        if (getParams[2] === undefined) {
                            if (docsObj[getParams[1]]) {
                                return new vscode.Hover([
                                    docsObj[getParams[1]].desc as string,
                                    docsObj[getParams[1]].line as string,
                                ]);
                            }
                        }
                        // (301,1)
                        else {
                            if (docsObj[getParams[1]][getParams[2]]) {
                                return new vscode.Hover([
                                    (<Record<string, string>>docsObj[getParams[1]][getParams[2]]).desc as string,
                                    (<Record<string, string>>docsObj[getParams[1]][getParams[2]]).line as string,
                                ]);
                            }
                        }
                    }
                } else {
                    return queryByWord();
                }
            }
        }
    }

    const hoverDisposable = vscode.languages.registerHoverProvider("*", {
        provideHover,
    });

    context.subscriptions.push(hoverDisposable);

    // 注册一个命令
    // const disposable = vscode.commands.registerCommand("extension.updateDocs", async () => {
    //     // 调用输入框，显示给用户
    //     const input = await vscode.window.showInputBox({
    //         prompt: "请输入新的提示文档内容",
    //         placeHolder: "在此输入...",
    //     });

    //     // 判断用户是否输入了内容
    //     if (input !== undefined) {
    //         console.log("input:", input);

    //         docsObj = formatData(input, true);
    //         // 全局保存
    //         context.globalState.update("docsObj", JSON.stringify(docsObj));
    //         console.log(formatData(input, true));
    //         vscode.window.showInformationMessage(`您输入了：${input}`);
    //     } else {
    //         vscode.window.showWarningMessage("操作已取消，没有输入任何内容。");
    //     }
    // });

    // // 将命令注册到上下文
    // context.subscriptions.push(disposable);

    function loadFile(filePath: string) {
        fs.readFile(filePath, "utf8", (err: { message: any }, data: any) => {
            if (err) {
                vscode.window.showErrorMessage(`读取文件失败: ${err.message}`);
            } else {
                vscode.window.showInformationMessage("文件加载成功！");
                console.log(data); // 输出文件内容
                const newData = formatData(data, true);

                docsObj = newData;

                console.log(docsObj); // 输出文件内容
                console.log(filePath); // 输出文件内容
            }
        });
    }

    {
        // 注册 选择字典 命令
        const disposable = vscode.commands.registerCommand("extension.selectDict", async () => {
            const fileUri = await vscode.window.showOpenDialog({
                canSelectMany: false,
                openLabel: "选择txt字典文件",
                filters: {
                    文本文件: ["txt"],
                    所有文件: [".txt"],
                },
            });

            if (fileUri && fileUri[0]) {
                const filePath = fileUri[0].fsPath;
                context.globalState.update("prevFileDir", filePath);
                loadFile(filePath);
            } else {
                vscode.window.showWarningMessage("未选择任何文件。");
            }
        });

        // 将命令注册到上下文
        context.subscriptions.push(disposable);
    }
}

export function deactivate() {}
